// challeng/pages/yplay/yplay.js
var app = getApp();
var answerTimer = null;
//amt为正数时颜色亮点，为负数时颜色暗点
function LightenDarkenColor(col, amt) {
	 var usePound = false;
	 if (col[0] == "#") {
		 col = col.slice(1);
		 usePound = true;
	 }
	 var num = parseInt(col,16);
	 var r = (num >> 16) + amt;
	 if (r > 255) r = 255;
	 else if (r < 0) r = 0;
	 var b = ((num >> 8) & 0x00FF) + amt;
	 if (b > 255) b = 255;
	 else if (b < 0) b = 0;
	 var g = (num & 0x0000FF) + amt;
	 if (g > 255) g = 255;
	 else if (g < 0) g = 0;
	 return (usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16);
}
function getRandomColor(){ 
	return "#"+("00000"+((Math.random()*16777215+0.5)>>0).toString(16)).slice(-6); 
} 
function getWidth(dimension){
	if(dimension==2) return 250;
	else if(dimension==3) return 200;
	else if(dimension==4) return 160;
	else if(dimension==5) return 120;
	else if(dimension==6) return 100;
	else if(dimension==7) return 80;
	else if(dimension==8) return 70;
	else if(dimension==9) return 60;
	else return 60;
}
Page({

  data: {
	game_bg:'',
	gametoken:'',
	openid:'',
	mem:{},
	total:0,
	cur_num:0,
	cur_i:0,
	times:[],
	g_nums:[],
	g_color:[],
	resettime:0,
	answerIng:false,
	tcolors:[],
	otherColor:'',
	twidth:0,//2维250rpx,3维200rpx,4维160rpx,5维120rpx,6维100rpx,7维80rpx,8维70rpx,9维60rpx
	
	beginCountDown: 3,//游戏开始--倒计时
	gamingStatus: 'notBegin',//游戏状态4个。notBegin未开始，running正在运行，fail挑战失败,success挑战成功
  },

  onLoad: function (options) {
	  var that = this;
	  wx.showLoading({title:'数据加载中...'});
	  app.sysInit(this,function(res){
		  app.getUserInfo(function (res) {
			  var openid = res['openid'];
			  //获取分享内容
			  app.getShareData(function(res){
				  that.setData({shareData:res.data});
			  },openid,7);
			  
			  that.setData({openid:openid});
			  app.util.request({
				  url: 'entry/wxapp/yplay',
				  data: {
					  m: 'junsion_challeng',
					  t: 1,
					  openid:openid,
					  game:7,
				  },
				  success: function (res) {
					  wx.hideLoading();
					  if(res.data.code==0 || res.data.code==2){
						  var code = res.data.code;
						  wx.showModal({
							  title:res.data.msg,
							  showCancel:false,
							  success: function(res) {
								  wx.showLoading({title:'数据加载中...'});
								  if(code==2)
									  var url = '../index/index?gobuy=1';
								  else var url = '../index/index';
								  wx.redirectTo({
									  url: url
								  })
							  }
						  });
					  }
					  else{
						  that.setData({
							  game_bg:res.data.game_bg,
							  gametoken:res.data.gametoken,
							  mem:res.data.mem,
							  beginCountDown:res.data.down,
							  total:res.data.total,
							  resettime:res.data.total_time,
							  times:res.data.times,
							  g_nums:res.data.g_nums,
							  g_color:res.data.g_color,
							  answerIng:false,
						  });
						  
						  if(parseInt(res.data.times[0])>0){
							  var dimension = parseInt(res.data.times[0]);
							  var color_val = parseInt(res.data.g_color[0]);
						  }
						  else if(parseInt(res.data.times[1])>0){
							  var dimension = parseInt(res.data.times[1]);
							  var color_val = parseInt(res.data.g_color[1]);
						  }
						  else if(parseInt(res.data.times[2])>0){
							  var dimension = parseInt(res.data.times[2]);
							  var color_val = parseInt(res.data.g_color[2]);
						  }
						  else{
							  var dimension = 9;
							  var color_val = 50;
						  }
						  if(dimension<2 || dimension>9) dimension = 9;
						  if(color_val<0 || color_val>255) color_val = 50;
						  var total_dimension = dimension * dimension;
						  var twidth = getWidth(dimension);
						  
						  var rand_xy = app.fRandomBy(0,total_dimension);
						  var rand_color = getRandomColor();
						  var otherColor = LightenDarkenColor(rand_color, color_val); 
						  
						  var tcolors = [];
						  for(var i=0;i<total_dimension;i++){
							  if(i==rand_xy)tcolors.push(otherColor);
							  else tcolors.push(rand_color);
						  }
						  that.setData({tcolors:tcolors,twidth:twidth,otherColor:otherColor});
						  that.beginCountDown(res.data.down);//游戏主入口
					  }
				  },
			  });
		  });
	  });
	  var music = wx.getStorageSync('music');
      that.setData({
		  music:music.music,
		  err_music:music.err_music,
	  });
  },
  onReady: function () {
	  var that=this;
  	  this.audioCtx = wx.createAudioContext('myAudio')
      this.errAudio = wx.createAudioContext('errAudio')
      this.audioCtx.play()
  },
  goCheck:function(e){
  	  var that = this;
	  var dataset = e.currentTarget.dataset;
	  var color = dataset.color;
	  var cur_num = parseInt(that.data.cur_num);
	  var otherColor = that.data.otherColor;
	  if(otherColor != color){
		  that.audioCtx.pause()
          app.tzfail(that,7);//挑战失败
		  return false;
	  }
	  else{
		  //回答正确，重新生成题目
		    cur_num++;
			if (cur_num == parseInt(that.data.total)) {
				that.audioCtx.pause()
				app.checkReward(that,7,cur_num);//中奖了
				return false;
			}
			if(parseInt(that.data.g_nums[0])>cur_num){
				var dimension=that.data.times[0];
				var color_val=that.data.g_color[0];
			}
			else if(parseInt(that.data.g_nums[1])>cur_num){
				var dimension=that.data.times[1];
				var color_val=that.data.g_color[1];
			}
			else if(parseInt(that.data.g_nums[2])>cur_num){
				var dimension=that.data.times[2];
				var color_val=that.data.g_color[2];
			}
			else{
				var dimension=9;
				var color_val=50;
			}
			if(dimension<2 || dimension>9) dimension = 9;
			if(color_val<0 || color_val>255) color_val = 50;
			var total_dimension = dimension * dimension;
			var twidth = getWidth(dimension);
		  
			var rand_xy = app.fRandomBy(0,total_dimension-1);
			var rand_color = getRandomColor();
			var otherColor = LightenDarkenColor(rand_color, parseInt(color_val)); 
			var tcolors = [];
			for(var i=0;i<total_dimension;i++){
			  if(i==rand_xy)tcolors.push(otherColor);
			  else tcolors.push(rand_color);
			}
			that.setData({tcolors:tcolors,twidth:twidth,cur_num:cur_num,otherColor:otherColor});
	  }
	  
  },  
  
  onUnload: function(){
	  clearInterval(answerTimer);
  },
  timeCountDown:function(myTime){
  	var that=this;
  	if(answerTimer){
  		clearInterval(answerTimer);
  		that.setData({ resettime: myTime });
  	}
		answerTimer = setInterval(function () {
  		if(that.data.answerIng){
  			return false;
  		}
  		that.setData({ resettime: --myTime });
  		if (myTime <= 0) {
  			//时间到，失败
  			clearInterval(answerTimer);
  			//失败处理
  			that.audioCtx.pause()
  			app.tzfail(that,7);//挑战失败
  		}
  	}, 1000);
  },
//游戏开始倒计时
  beginCountDown:function(countTime){
      var that=this;
      var timer = setInterval(function () {
          that.setData({ beginCountDown: --countTime });
          if (countTime <= 0) {
              clearInterval(timer);
              that.setData({
                  gamingStatus:'running'
              });
              that.timeCountDown(parseInt(that.data.resettime));//游戏主入口
          }
      }, 1000)
  },
  
  onShareAppMessage:function(){
	  var that = this;
	  var mid = that.data.mem.id;
	  var sharedata = that.data.shareData;
	  sharedata.path = 'challeng/pages/index/index?mid='+mid+'&gType=7';
	  return {
		  title: sharedata.title,
	     // desc: sharedata.desc,
	      path: sharedata.path,
	      imageUrl:sharedata.pic,
	      success(res){
	    	  var shareTicket = res.shareTickets[0] // 获取 shareTicket
	    	  wx.getShareInfo({
	              shareTicket: shareTicket,
	              complete(res) {
	            	  app.util.request({
		    	        url: 'entry/wxapp/addnums',
		    	        data: {
		    	            m : 'junsion_challeng',
		    	            t : 1,
		    	            mid : that.data.openid,
		    	            iv : res.iv,
		    	            encryptedData : res.encryptedData,
		    	        },
		    	        success: function (res) {
		    	        	if (res.data.code == 1) {
		                        that.setData({ challeng_num: parseInt(res.data.num)});
	                        	wx.showToast({
	                        		title:'次数\t+'+res.data.num,
	                        		icon:'none',
	                				mask:true,
	                				duration:1000
	                			});
		    	    	    } 
		    	        	else{
		    	        		 wx.showModal({title:res.data.msg,showCancel:false});
		    	        	}
		    	        }
		    	    }); 
	                
	              }
	          });
	      },
	      fail: function(res) {
	        // 转发失败
	    	  console.log(res);
	      }
	  }
  },
})